﻿/*
 * Copyright (C) 2023 - 2024 lchfj.cn
 * 
 * This file is part of FastestHost.
 * 
 * FastestHost is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * FastestHost is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with FastestHost. If not, see <https://www.gnu.org/licenses/>.
 */

using System.Collections.Concurrent;

namespace Cn.Lchfj.FastestHost;

internal class TestContainer
{
    private readonly string Host;
    private readonly HostIP[] AllList;
    private readonly HostIPTest Tester;
    private int currentIndex;
    private int lastIndex = 0;
    private int lastTimes = 0;

    public TestContainer(IGrouping<string, HostIP> list, HostIPTest tester)
    {
        Host = list.Key;
        AllList = [.. list];
        Tester = tester;

        currentIndex = -1;
        TestResult = [];
    }

    public ConcurrentBag<HostIPTestResult> TestResult { get; internal set; }

    internal async Task WaitToEnd()
    {
        var taskCount = Math.Min(32, AllList.Length);
        for (var i = 0; i < taskCount; i++)
            ThreadPool.QueueUserWorkItem(Check);

        ConsoleHelper.WriteLine($"正在测试【{Host}】的访问时间（{taskCount} / {AllList.Length}）");
        while (true)
        {
            await Task.Delay(1000);
            if (TestResult.Count == AllList.Length)
                break;

            if (lastIndex == currentIndex)
            {
                lastTimes++;
                if (lastTimes > 60)
                    break;
            }
            else
            {
                lastIndex = currentIndex;
                lastTimes = 0;
            }

            var current = Math.Min(currentIndex + 1, AllList.Length);
            ConsoleHelper.WriteLine($"正在测试【{Host}】的访问时间（{current} / {AllList.Length}）");
        }

        ConsoleHelper.WriteLine();
    }

    private async void Check(object? state)
    {
        while (currentIndex < AllList.Length - 1)
        {
            var index = Interlocked.Increment(ref currentIndex);
            if (index >= AllList.Length)
                break;

            var ip = AllList[index];

            var result = await Tester.TestAsync(ip);
            TestResult.Add(result);
        }
    }
}